package com.cqx.collection.scheduler;

import com.cqx.collection.persistence.entity.ManufactureView;
import com.cqx.collection.persistence.repository.ManufactureRepository;
import com.cqx.collection.util.DateUtil;
import com.cqx.collection.web.vo.SquareQuantityDataVO;
import com.cqx.collection.web.vo.SquareQuantityVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 推送数据
 **/
@Component
public class PushDateScheduler {

    private static Logger logger= LoggerFactory.getLogger(PushDateScheduler.class);

    @Value("${blender.id}")
    private String blenderId;

    @Value("${blender.url}")
    private String blenderUrl;

    @Value("${blender.line}")
    private Integer blenderLine;

    @Value("${acquisitionStartTime}")
    private String acquisitionStartTime;

    @Autowired
    private RestTemplate simpleRestTemplate;

    @Autowired
    private ManufactureRepository manufactureRepository;

    @Scheduled(cron = "${pushDateCron}")
    public void pushDate() {
        logger.info("=======================数据推送开始启动=======================");
        //获取上次最后推送时间
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> sentryRequestEntity = new HttpEntity<String>("", httpHeaders);
        ResponseEntity<String> responseEntity = null;
        try {
            String requestUrl = blenderUrl + "/dataAcquisition/queryPushLastDate"+"?blenderId="+blenderId+"&line="+blenderLine;
            responseEntity = simpleRestTemplate.exchange(requestUrl, HttpMethod.GET, sentryRequestEntity, String.class);
            String time = null;
            if(!StringUtils.isEmpty(responseEntity.getBody())){
                time = responseEntity.getBody();
            }else{
                //第一次推送
                time = acquisitionStartTime;
            }
            Date date = DateUtil.rollDay(DateUtil.stringToDate(time,DateUtil.YYYYMMDDHHMMSS),7);
            List<ManufactureView> manufactureViewList = manufactureRepository.findByTimeBetween(DateUtil.strToDateLong(time),date);
            push(manufactureViewList);
            while (date.before(new Date())){
                Date endDate = DateUtil.rollDay(date,7);
                List<ManufactureView> manufactureViews = manufactureRepository.findByTimeBetween(date,endDate);
                push(manufactureViews);
                date = endDate;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 传输数据
     * @param manufactureViewList
     */
    public void push(List<ManufactureView> manufactureViewList){
        if(!manufactureViewList.isEmpty()){
            SquareQuantityVO squareQuantityVO = new SquareQuantityVO();
            squareQuantityVO.setBlenderId(blenderId);
            squareQuantityVO.setBlenderLine(blenderLine);
            List<SquareQuantityDataVO> squareQuantityDataVOList = new ArrayList<>();
            for(ManufactureView manufactureView:manufactureViewList){
                SquareQuantityDataVO squareQuantityDataVO = new SquareQuantityDataVO();
                squareQuantityDataVO.setSquareQuantityId(manufactureView.getId());
                squareQuantityDataVO.setSquareQuantity(manufactureView.getSquareQuantity());
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date parsedDate = null;
                try {
                    parsedDate = dateFormat.parse(manufactureView.getTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Timestamp timestamp = new Timestamp(parsedDate.getTime());
                squareQuantityDataVO.setTime(timestamp);
                squareQuantityDataVOList.add(squareQuantityDataVO);
            }
            squareQuantityVO.setSquareQuantityDataIOList(squareQuantityDataVOList);

            HttpHeaders httpHeadersPush = new HttpHeaders();
            httpHeadersPush.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> sentryRequestEntityPush = new HttpEntity(squareQuantityVO, httpHeadersPush);
            ResponseEntity<Boolean> responseEntityPush = null;

            String requestUrlPush = blenderUrl + "/dataAcquisition/squareQuantity";
            responseEntityPush = simpleRestTemplate.exchange(requestUrlPush, HttpMethod.POST, sentryRequestEntityPush, Boolean.class);

            if(responseEntityPush.getBody()){
                logger.info("=======================数据推送运行完成=======================");
            }
        }else{
            logger.info("=======================没有推送数据=======================");
        }
    }
}
